import { areaData } from '../config/index';

const addressParse = (provinceName, cityName, countryName) => {
  return new Promise((resolve, reject) => {
    try {
      const province = areaData.find((v) => v.label === provinceName);
      const { value: provinceCode } = province;
      const city = province.children.find((v) => v.label === cityName);
      const { value: cityCode } = city;
      const country = city.children.find((v) => v.label === countryName);
      const { value: districtCode } = country;
      resolve({
        provinceCode,
        cityCode,
        districtCode,
      });
    } catch (error) {
      reject('地址解析失败');
    }
  });
};

// 定义常量
const R = 6371; // 地球平均半径，单位为公里
// 将度数转换为弧度
const toRadians = (degrees) => {
  return degrees * (Math.PI / 180);
}

const calculateDistance = (lat1, lon1, lat2, lon2) => {
  const Y1 = toRadians(lat1);
  const Y2 = toRadians(lat2);
  const X1 = toRadians(lon1);
  const X2 = toRadians(lon2);

  const distance = R * Math.acos(
    Math.cos(Y1) * Math.cos(Y2) * Math.cos(X1 - X2) +
    Math.sin(Y1) * Math.sin(Y2)
  );

  return distance;
};

module.exports = {
  addressParse, calculateDistance,
};
